package com.bdqn.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bdqn.pojo.User;
import com.bdqn.service.RedisService;
import com.bdqn.util.JedisUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.io.Serializable;
import java.util.Date;
import java.util.UUID;


@Slf4j
@Service
public class RedisServiceImpl implements RedisService {

    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public String generateToken(User user) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 在key中有冒号（:）将会创建一个组（文件夹）
        try (Jedis jedis = JedisUtil.getJedis()) {
            String token_key = "token:" + uuid;
            String session_key = "session:" + uuid;
            // 将用户对象存储到Redis
            jedis.set(token_key, JSON.toJSONString(user));
            // 测试，存储一些用户自己的东西在Redis
            jedis.hset(session_key, "token", token_key);
            jedis.hset(session_key, "loginTime", new Date().toString());
        }
        return uuid;
    }


    @Override
    public User checkToken(String token) {
        String jsonLoginUser = null;
        try (Jedis jedis = JedisUtil.getJedis()) {
            String token_key = "token:" + token;
            // 获取Redis中的用户对象
            jsonLoginUser = jedis.get(token_key);
            if (jsonLoginUser == null) {
                return null;
            }
        }
        return JSONObject.parseObject(jsonLoginUser, User.class);
    }


    @Override
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            log.error("set error: key {}, value {}", key, value, e);
        }
        return result;
    }

}
